﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EasierRdp.Models;
using EasierRdp.Util;

namespace EasierRdp
{
    partial class AddServerDialog : Form
    {
        public RdpUser User { get; set; }
        public RdpGroup Group { get; set; }

        public AddServerDialog()
        {
            InitializeComponent();
            this.DialogResult = DialogResult.None;
        }

        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == EasierRdpEvents.ServerDialog.ShowDialog(EasierRdpEvents.MainForm))
            {
                RebindList();
            }
        }

        private void AddServerDialog_Load(object sender, EventArgs e)
        {
            RebindList();
        }

        private void RebindList()
        {
            ServerList.Items.Clear();
            foreach (var rdpServer in RdpContext.Servers)
            {
                var index = ServerList.Items.Add(rdpServer.Value);
                if ((User != null && User.Servers.Any(s => s.Id == rdpServer.Key))
                    || (Group != null && Group.Servers.Any(s => s.Id == rdpServer.Key)))
                {
                    ServerList.SetItemChecked(index,true);
                }
            }
        }

        private void ButtonOk_Click(object sender, EventArgs e)
        {
            var servers = ServerList.CheckedItems.Cast<RdpServer>().ToList();
            var serverRefs = servers.Select(r => new RdpServerRef(r.Id)).ToList();
            if (User != null)
            {
                User.Servers.Clear();
                foreach (var rdpServerRef in serverRefs)
                {
                    User.Servers.Add(rdpServerRef);
                }
                foreach (var rdpServer in servers)
                {
                    if (rdpServer.Users.All(u => u.Id != User.Id))
                    {
                        rdpServer.Users.Add(new RdpUserRef(User.Id));
                    }
                }
            }
            if (Group != null)
            {
                Group.Servers.Clear();
                foreach (var rdpServer in servers)
                {
                    Group.Servers.Add(rdpServer);
                }
            }
            EasierRdpEvents.RebindTreeView();
            this.DialogResult = DialogResult.OK;
        }

        private void ButtonCancel_Click(object sender, EventArgs e)
        {
            this.Hide();
        }
    }
}
